const dao = require('./base');

module.exports = {

    peerList: async function (condition, fields = "*", by = []) {
        let sql = `SELECT ${fields} from afc_peer a left join afc_msp b on a.mid = b.mid where a.del_flag=0`;
        let pre = [];
        if (condition.peer !== undefined && condition.peer !== '') {
            sql += ` and a.peer like %?%`;
            pre.push(condition.peer);
        }

        if (condition.mid !== undefined && condition.mid !== '') {
            sql += ` and a.mid = ?`;
            pre.push(condition.mid);
        }
        sql = dao.by(sql, by)

        let limit = dao.limit(sql, condition, pre);
        sql = limit.sql;
        pre = limit.pre;

        let data;
        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    peerAdd: async function (fields = []) {
        let sql = "insert into afc_peer (peer,mid,p_address,p_tls) values(?,?,?,?)";
        let pre = [];
        let data;
        pre.push(fields.peer);
        pre.push(fields.mid);
        pre.push(fields.p_address);
        pre.push(fields.p_tls);

        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    peerUpdate: async function (condition = {}, fields = {}) {
        let sql = "update afc_peer set ";
        let pre = [];
        let data;
        if (fields.peer !== undefined && fields.peer !== '') {
            sql = dao.update_sql_splice(sql, "peer");
            pre.push(fields.peer);
        }
        if (fields.mid !== undefined && fields.mid !== '') {
            sql = dao.update_sql_splice(sql, "mid");
            pre.push(fields.mid);
        }
        if (fields.p_address !== undefined && fields.p_address !== '') {
            sql = dao.update_sql_splice(sql, "p_address");
            pre.push(fields.p_address);
        }
        if (fields.p_tls !== undefined && fields.p_tls !== '') {
            sql = dao.update_sql_splice(sql, "p_tls");
            pre.push(fields.p_tls);
        }
        if (fields.del_flag !== undefined && fields.del_flag !== '') {
            sql = dao.update_sql_splice(sql, "del_flag");
            pre.push(fields.del_flag);
        }
        if (condition.pid !== undefined && condition.pid !== '') {
            sql += ` where pid = ?`;
            pre.push(condition.pid);
        } else {
            return;
        }

        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },


};
